package zxs.sino.elite.hub.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 *
 * @author zhang
 */
@Component
public class RedisUtil {

    private final RedisTemplate<String, Object> redisTemplate;
    private final ValueOperations<String, Object> valueOperations;
    private final SetOperations<String, Object> setOperations;
    private final ZSetOperations<String, Object> zSetOperations;

    @Autowired
    public RedisUtil(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.valueOperations = redisTemplate.opsForValue();
        this.setOperations = redisTemplate.opsForSet();
        this.zSetOperations = redisTemplate.opsForZSet();
    }

    /**
     * 不设置过期时长
     */
    public final static long NOT_EXPIRE = -1;
    private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();


    /**
     * 将对象数据存储到redis中
     */
    public void set(String key, Object value, long expire) {
        valueOperations.set(key, toJson(value));
        if (expire != NOT_EXPIRE) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
    }

    /**
     * 将redis中数据转换成对象
     */
    public <T> T get(String key, Class<T> clazz) {
        String value = Objects.requireNonNull(valueOperations.get(key)).toString();
        return value == null ? null : fromJson(value, clazz);
    }

    /**
     * 获取redis中值
     */
    public Object get(String key) {
        return valueOperations.get(key);
    }


    /**
     * 获取redis中的key
     */
    public Set<String> keys(String key) {
        return redisTemplate.keys(key);
    }

    /**
     * 将redis中对应的键删除
     */
    public void delete(String key) {
        redisTemplate.delete(key);
    }

    /**
     * 将对象数据存储到redis中
     */
    public void setSet(String key, Object value) {
        setOperations.add(key, value);
    }

    /**
     * 将对象数据存储到redis中
     */
    public Set<Object> setGet(String key) {
        return setOperations.members(key);
    }

    /**
     * 将对象数据在redis中删除
     */
    public void setDelete(String key, Object value) {
        setOperations.remove(key, value);
    }

    /**
     * 判断对象在redis中是否存在
     */
    public boolean isMember(String key, Object value) {
        return Boolean.TRUE.equals(setOperations.isMember(key, value));
    }

    /**
     * 获取key对应的数量
     */
    public Long getCount(String key) {
        return setOperations.size(key);
    }

    /**
     * 追加计数器量
     */
    public void incrementCounter(String key, long delta) {
        valueOperations.increment(key, delta);
    }

    /**
     * 删除计数器量
     */
    public void decrementCounter(String key, long delta) {
        valueOperations.decrement(key, delta);
    }

    /**
     * Object转成JSON数据
     */
    private String toJson(Object object) {
        if (object instanceof Integer || object instanceof Long || object instanceof Float ||
                object instanceof Double || object instanceof Boolean || object instanceof String) {
            return String.valueOf(object);
        }
        try {
            return OBJECT_MAPPER.writeValueAsString(object);
        } catch (Exception e) {
            throw new RuntimeException("Failed to convert object to JSON", e);
        }
    }

    /**
     * JSON数据，转成Object
     */
    private <T> T fromJson(String json, Class<T> clazz) {
        try {
            return OBJECT_MAPPER.readValue(json, clazz);
        } catch (Exception e) {
            throw new RuntimeException("Failed to convert JSON to object", e);
        }
    }
}
